<!-- 采购管理-采购任务列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div class="search-box">
    <a-space>
      <div class="content-head">
        <a-input-group>
          <a-input-search
            :style="{ width: 'auto' }"
            placeholder="请输入采购任务单号"
            @search="search"
            v-model="currSelectSearch"
            search-button
          />
        </a-input-group>
      </div>

      <div>
        <a-select placeholder="请选择" v-model="userState" @change="search">
          <template #prefix>状态：</template>
          <a-option :value="1">待执行</a-option>
          <a-option :value="3">执行中</a-option>
          <a-option :value="4">已完成</a-option>
          <a-option :value="0">全部</a-option>
        </a-select>
      </div>
      <div
        :style="{
          display: 'flex',
        }"
      >
        <div
          :style="{
            lineHeight: '30px',
          }"
        ></div>
        <div>
          <a-select
            v-model="priorityData"
            placeholder="请选择"
            @change="search"
          >
            <template #prefix>优先级：</template>
            <a-option :value="1">低</a-option>
            <a-option :value="2">中</a-option>
            <a-option :value="3">高</a-option>
            <a-option :value="4">紧急</a-option>
            <a-option :value="0">全部</a-option>
          </a-select>
        </div>
      </div>
      <a-button type="outline" @click="reset">
        <template #icon>
          <icon-refresh />
        </template>
        <template #default>重置</template>
      </a-button>
    </a-space>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.name"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.code"
        align="center"
        :width="150"
        :sortable="{
          sortDirections: ['ascend', 'descend'],
        }"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <!-- 明细  -->
        <template v-if="item.code === 'taskDetail'" #cell="{ record }">
          <!-- <a-typography-text
            style="cursor: pointer"
            type="primary"
            @click="See(record)"
          >
            查看
          </a-typography-text> -->
          <a-tooltip content="查看">
            <IconFont
              type="icon-chakan1"
              :size="30"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="See(record)"
            />
          </a-tooltip>
        </template>

        <!-- 原因 -->
        <template
          v-else-if="item.code === 'taskDescription'"
          #cell="{ record }"
        >
          <!-- <a-typography-text
            style="cursor: pointer"
            type="primary"
            @click="view(record.description)"
          >
            查看
          </a-typography-text> -->
          <a-tooltip content="查看">
            <IconFont
              type="icon-chakan1"
              :size="30"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="view(record.description)"
            />
          </a-tooltip>
        </template>
        <!-- 申请日期 -->
        <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <!-- 开始时间 -->
        <template v-else-if="item.code === 'beginTime'" #cell="{ record }">
          {{ dayjs(record.beginTime).format('YYYY-MM-DD') }}
        </template>
        <!-- 开始时间 -->
        <template v-else-if="item.code === 'endTime'" #cell="{ record }">
          {{
            record.endTime ? dayjs(record.endTime).format('YYYY-MM-DD') : '无'
          }}
        </template>
        <!-- 优先级 -->
        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <!-- 状态 -->
        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="100" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip
            v-if="record.state === 1 || record.state === 2"
            content="执行"
          >
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetails(record.id, 1)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state === 3" content="进入任务">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetails(record.id, 2)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state === 4" content="查看详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetails(record.id, 3)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
      <!-- <a-table-column :width="80" align="center">
          <template #title> <icon-settings /> </template>
        </a-table-column> -->
    </tableTurn>
  </div>

  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="采购任务列表"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <ViewDetails v-model:visible="modelVisible" :taskId="taskId"> </ViewDetails>
  <ViewCause
    v-model:visible="modelCauseVisible"
    :SeeCauseDate="SeeCauseDate"
  ></ViewCause>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
  } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchasetaskList,
  } from '@/api/buy-management/buy-task/index';

  let ViewDetails = defineAsyncComponent(
    () => import('./view-details/index.vue')
  );
  let ViewCause = defineAsyncComponent(() => import('./view-cause/index.vue'));
  // import ViewCause from './view-cause/index.vue';
  const taskId = ref();
  const router = useRouter();
  const title: string = '采购任务列表';
  const breadCrumb: string[] = ['采购管理', '采购管理', '采购任务列表'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const userState = ref();
  const beginTime = ref();
  const endTime = ref();
  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive({
    list: [],
  });

  // 表格配置
  const args = reactive({
    stripe: true,
    // scroll: {
    //   y: 500,
    // },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const orderStatus = [
    { id: 1, value: '待确认', backgroundColor: '#cccccc' },
    { id: 2, value: '待执行', backgroundColor: '#cccccc' },
    { id: 3, value: '执行中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '已完成', backgroundColor: '#009933' },
  ];

  const columns = [
    { code: 'number', isDefault: 1, name: '采购任务单号' },
    { code: 'priority', isDefault: 1, name: '优先级' },
    { code: 'taskDetail', isDefault: 1, name: '任务明细' },
    { code: 'taskDescription', isDefault: 1, name: '任务描述' },
    { code: 'createdAt', isDefault: 1, name: '任务下达时间' },
    { code: 'createByName', isDefault: 1, name: '下达人' },
    { code: 'executeByName', isDefault: 1, name: '执行人' },
    { code: 'beginTime', isDefault: 1, name: '任务开始时间' },
    { code: 'endTime', isDefault: 1, name: '任务结束时间' },
    { code: 'okState', isDefault: 1, name: '执行状态' },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await getPurchaseHeader({ userId: 317, listType: 4 });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    beginTime.value = undefined;
    endTime.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  // const del = async (id) => {
  //   await delPurchasetaskList({ id });
  //   tableRef.value.loadData();
  // };

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (beginTime.value !== '' && endTime.value !== '') {
        msg.beginTime = beginTime.value;
        msg.endTime = endTime.value;
      }
      const res = await getPurchasetaskList({
        ...pageData,
        ...msg,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const headerSave = async (val) => {
    try {
      const data = {
        userId: 317,
        listType: 4,
        extend: JSON.stringify(val),
      };
      await PUTPurchaseHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeCauseDate = ref();
  const view = (content: string) => {
    SeeCauseDate.value = content;
    modelCauseVisible.value = true;
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const See = (item: any) => {
    modelVisible.value = true;
    taskId.value = item.id;
  };

  const goDetails = (id: number, state: number) => {
    router.push({
      name: 'DetailedTaskPurchaseList',
      query: { id, state },
    });
  };
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
